import 'package:flutter/material.dart';
import 'package:provider/provider.dart';
import '../providers/subscription_provider.dart';
import '../providers/vpn_provider.dart';
import '../models/subscription.dart';
import '../widgets/subscription_update_result_dialog.dart';
import 'package:intl/intl.dart';

class SubscriptionsScreen extends StatelessWidget {
  const SubscriptionsScreen({super.key});

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('Subscriptions'),
        actions: [
          IconButton(
            icon: const Icon(Icons.refresh),
            onPressed: () async {
              final provider = Provider.of<SubscriptionProvider>(context, listen: false);
              
              // 显示正在更新的对话框
              showDialog(
                context: context,
                barrierDismissible: false,
                builder: (context) => const Center(
                  child: Card(
                    child: Padding(
                      padding: EdgeInsets.all(24),
                      child: Column(
                        mainAxisSize: MainAxisSize.min,
                        children: [
                          CircularProgressIndicator(),
                          SizedBox(height: 16),
                          Text(
                            'Updating all subscriptions...',
                            style: TextStyle(fontSize: 16),
                          ),
                        ],
                      ),
                    ),
                  ),
                ),
              );
              
              final results = await provider.updateAllSubscriptions();
              
              if (context.mounted) {
                Navigator.pop(context); // 关闭加载对话框
                
                // 显示汇总结果
                _showBatchUpdateResults(context, results);
              }
            },
            tooltip: 'Update All',
          ),
          IconButton(
            icon: const Icon(Icons.add),
            onPressed: () {
              _showAddSubscriptionDialog(context);
            },
            tooltip: 'Add Subscription',
          ),
        ],
      ),
      body: Consumer<SubscriptionProvider>(
        builder: (context, provider, _) {
          if (provider.subscriptions.isEmpty) {
            return Center(
              child: Column(
                mainAxisAlignment: MainAxisAlignment.center,
                children: [
                  Icon(
                    Icons.subscriptions_outlined,
                    size: 64,
                    color: Colors.grey.shade400,
                  ),
                  const SizedBox(height: 16),
                  Text(
                    'No subscriptions',
                    style: TextStyle(
                      fontSize: 16,
                      color: Colors.grey.shade600,
                    ),
                  ),
                  const SizedBox(height: 16),
                  ElevatedButton.icon(
                    onPressed: () {
                      _showAddSubscriptionDialog(context);
                    },
                    icon: const Icon(Icons.add),
                    label: const Text('Add Subscription'),
                  ),
                ],
              ),
            );
          }

          return ListView.builder(
            padding: const EdgeInsets.all(16),
            itemCount: provider.subscriptions.length,
            itemBuilder: (context, index) {
              final subscription = provider.subscriptions[index];
              return _SubscriptionCard(
                subscription: subscription,
                onUpdate: () async {
                  await _updateSubscription(context, subscription);
                },
                onEdit: () {
                  _showEditSubscriptionDialog(context, subscription);
                },
                onDelete: () {
                  _confirmDelete(context, subscription);
                },
                onDeleteServers: () {
                  _confirmDeleteServers(context, subscription);
                },
              );
            },
          );
        },
      ),
    );
  }

  Future<void> _updateSubscription(BuildContext context, Subscription subscription) async {
    final provider = Provider.of<SubscriptionProvider>(context, listen: false);
    
    // 显示正在更新的对话框
    showDialog(
      context: context,
      barrierDismissible: false,
      builder: (context) => Center(
        child: Card(
          child: Padding(
            padding: const EdgeInsets.all(24),
            child: Column(
              mainAxisSize: MainAxisSize.min,
              children: [
                const CircularProgressIndicator(),
                const SizedBox(height: 16),
                Text(
                  'Updating "${subscription.name}"...',
                  style: const TextStyle(fontSize: 16),
                ),
              ],
            ),
          ),
        ),
      ),
    );
    
    try {
      final result = await provider.updateServersFromSubscription(subscription.id);
      
      if (context.mounted) {
        Navigator.pop(context); // 关闭加载对话框
        
        // 显示更新结果
        showDialog(
          context: context,
          builder: (context) => SubscriptionUpdateResultDialog(result: result),
        );
      }
    } catch (e) {
      if (context.mounted) {
        Navigator.pop(context); // 关闭加载对话框
        
        ScaffoldMessenger.of(context).showSnackBar(
          SnackBar(
            content: Row(
              children: [
                const Icon(Icons.error_outline, color: Colors.white),
                const SizedBox(width: 12),
                Expanded(child: Text('Update failed: $e')),
              ],
            ),
            backgroundColor: Colors.red,
          ),
        );
      }
    }
  }

  void _showBatchUpdateResults(BuildContext context, List<SubscriptionUpdateResult> results) {
    final totalAdded = results.fold<int>(0, (sum, r) => sum + r.addedCount);
    final totalRemoved = results.fold<int>(0, (sum, r) => sum + r.removedCount);
    final totalUnchanged = results.fold<int>(0, (sum, r) => sum + r.unchangedCount);
    final hasChanges = totalAdded > 0 || totalRemoved > 0;

    showDialog(
      context: context,
      builder: (context) => Dialog(
        shape: RoundedRectangleBorder(borderRadius: BorderRadius.circular(20)),
        child: Container(
          constraints: const BoxConstraints(maxWidth: 500, maxHeight: 600),
          child: Column(
            mainAxisSize: MainAxisSize.min,
            children: [
              // 头部
              Container(
                padding: const EdgeInsets.all(20),
                decoration: BoxDecoration(
                  color: hasChanges 
                      ? Theme.of(context).colorScheme.primary
                      : Colors.grey.shade600,
                  borderRadius: const BorderRadius.vertical(top: Radius.circular(20)),
                ),
                child: Row(
                  children: [
                    Icon(
                      hasChanges ? Icons.check_circle : Icons.info,
                      color: Colors.white,
                      size: 28,
                    ),
                    const SizedBox(width: 12),
                    const Expanded(
                      child: Text(
                        'All Subscriptions Updated',
                        style: TextStyle(
                          color: Colors.white,
                          fontSize: 20,
                          fontWeight: FontWeight.bold,
                        ),
                      ),
                    ),
                    IconButton(
                      icon: const Icon(Icons.close, color: Colors.white),
                      onPressed: () => Navigator.pop(context),
                    ),
                  ],
                ),
              ),

              // 总统计
              Padding(
                padding: const EdgeInsets.all(16),
                child: Row(
                  children: [
                    Expanded(
                      child: _buildStatCard(
                        context,
                        Icons.add_circle,
                        '$totalAdded',
                        'Added',
                        Colors.green,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: _buildStatCard(
                        context,
                        Icons.remove_circle,
                        '$totalRemoved',
                        'Removed',
                        Colors.red,
                      ),
                    ),
                    const SizedBox(width: 12),
                    Expanded(
                      child: _buildStatCard(
                        context,
                        Icons.check_circle_outline,
                        '$totalUnchanged',
                        'Unchanged',
                        Colors.blue,
                      ),
                    ),
                  ],
                ),
              ),

              // 各订阅详情
              Expanded(
                child: ListView.builder(
                  padding: const EdgeInsets.symmetric(horizontal: 16),
                  itemCount: results.length,
                  itemBuilder: (context, index) {
                    final result = results[index];
                    return Card(
                      margin: const EdgeInsets.only(bottom: 12),
                      child: ListTile(
                        leading: Icon(
                          result.hasChanges ? Icons.check_circle : Icons.info,
                          color: result.hasChanges ? Colors.green : Colors.grey,
                        ),
                        title: Text(result.subscriptionName),
                        subtitle: Text(
                          '+${result.addedCount} / -${result.removedCount} / =${result.unchangedCount}',
                          style: TextStyle(
                            color: Colors.grey.shade600,
                            fontSize: 12,
                          ),
                        ),
                        trailing: result.hasChanges
                            ? TextButton(
                                onPressed: () {
                                  Navigator.pop(context);
                                  showDialog(
                                    context: context,
                                    builder: (context) => SubscriptionUpdateResultDialog(result: result),
                                  );
                                },
                                child: const Text('Details'),
                              )
                            : null,
                      ),
                    );
                  },
                ),
              ),

              // 底部按钮
              Container(
                padding: const EdgeInsets.all(16),
                decoration: BoxDecoration(
                  color: Colors.grey.shade50,
                  border: Border(top: BorderSide(color: Colors.grey.shade200)),
                ),
                child: Row(
                  mainAxisAlignment: MainAxisAlignment.end,
                  children: [
                    ElevatedButton(
                      onPressed: () => Navigator.pop(context),
                      style: ElevatedButton.styleFrom(
                        backgroundColor: Theme.of(context).colorScheme.primary,
                        foregroundColor: Colors.white,
                        padding: const EdgeInsets.symmetric(horizontal: 24, vertical: 12),
                      ),
                      child: const Text('Close'),
                    ),
                  ],
                ),
              ),
            ],
          ),
        ),
      ),
    );
  }

  Widget _buildStatCard(
    BuildContext context,
    IconData icon,
    String value,
    String label,
    Color color,
  ) {
    return Container(
      padding: const EdgeInsets.all(12),
      decoration: BoxDecoration(
        color: color.withOpacity(0.1),
        borderRadius: BorderRadius.circular(12),
        border: Border.all(color: color.withOpacity(0.3)),
      ),
      child: Column(
        children: [
          Icon(icon, color: color, size: 24),
          const SizedBox(height: 8),
          Text(
            value,
            style: TextStyle(
              fontSize: 20,
              fontWeight: FontWeight.bold,
              color: color,
            ),
          ),
          const SizedBox(height: 4),
          Text(
            label,
            style: TextStyle(
              fontSize: 11,
              color: Colors.grey.shade700,
              fontWeight: FontWeight.w500,
            ),
          ),
        ],
      ),
    );
  }

  void _showAddSubscriptionDialog(BuildContext context) {
    final nameController = TextEditingController();
    final urlController = TextEditingController();

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Add Subscription'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: 'Name',
                hintText: 'Enter subscription name',
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: urlController,
              decoration: const InputDecoration(
                labelText: 'URL',
                hintText: 'Enter subscription URL',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              final name = nameController.text.trim();
              final url = urlController.text.trim();

              if (name.isNotEmpty && url.isNotEmpty) {
                final subscription = Subscription(
                  id: DateTime.now().millisecondsSinceEpoch.toString(),
                  name: name,
                  url: url,
                );

                final provider = Provider.of<SubscriptionProvider>(
                  context,
                  listen: false,
                );
                provider.addSubscription(subscription);
                provider.updateServersFromSubscription(subscription.id);

                Navigator.pop(context);
              }
            },
            child: const Text('Add'),
          ),
        ],
      ),
    );
  }

  void _showEditSubscriptionDialog(BuildContext context, Subscription subscription) {
    final nameController = TextEditingController(text: subscription.name);
    final urlController = TextEditingController(text: subscription.url);

    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Edit Subscription'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          children: [
            TextField(
              controller: nameController,
              decoration: const InputDecoration(
                labelText: 'Name',
              ),
            ),
            const SizedBox(height: 16),
            TextField(
              controller: urlController,
              decoration: const InputDecoration(
                labelText: 'URL',
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              final updatedSubscription = Subscription(
                id: subscription.id,
                name: nameController.text.trim(),
                url: urlController.text.trim(),
                lastUpdate: subscription.lastUpdate,
                serverCount: subscription.serverCount,
                autoUpdate: subscription.autoUpdate,
                updateInterval: subscription.updateInterval,
              );

              final provider = Provider.of<SubscriptionProvider>(
                context,
                listen: false,
              );
              provider.updateSubscription(updatedSubscription);

              Navigator.pop(context);
            },
            child: const Text('Save'),
          ),
        ],
      ),
    );
  }

  void _confirmDelete(BuildContext context, Subscription subscription) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    // 计算该订阅分组下的服务器数量
    final serversInGroup = vpnProvider.allServers
        .where((s) => s.group == subscription.name)
        .length;
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: const Text('Delete Subscription'),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text('Are you sure you want to delete "${subscription.name}"?'),
            if (serversInGroup > 0) ...[
              const SizedBox(height: 12),
              Container(
                padding: const EdgeInsets.all(12),
                decoration: BoxDecoration(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.orange.shade900.withOpacity(0.2)
                      : Colors.orange.shade50,
                  borderRadius: BorderRadius.circular(8),
                  border: Border.all(
                    color: Theme.of(context).brightness == Brightness.dark
                        ? Colors.orange.shade700.withOpacity(0.5)
                        : Colors.orange.shade200,
                  ),
                ),
                child: Row(
                  children: [
                    Icon(Icons.warning_amber_rounded, color: Colors.orange.shade700, size: 20),
                    const SizedBox(width: 8),
                    Expanded(
                      child: Text(
                        'This will also delete $serversInGroup server${serversInGroup > 1 ? 's' : ''} in this group.',
                        style: TextStyle(
                          fontSize: 13,
                          color: Theme.of(context).brightness == Brightness.dark
                              ? Colors.orange.shade300
                              : Colors.orange.shade900,
                        ),
                      ),
                    ),
                  ],
                ),
              ),
            ],
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          TextButton(
            onPressed: () {
              final provider = Provider.of<SubscriptionProvider>(
                context,
                listen: false,
              );
              provider.deleteSubscription(subscription.id);
              Navigator.pop(context);
              
              // 显示删除成功的消息
              ScaffoldMessenger.of(context).showSnackBar(
                SnackBar(
                  content: Row(
                    children: [
                      const Icon(Icons.check_circle, color: Colors.white),
                      const SizedBox(width: 12),
                      Expanded(
                        child: Text(
                          'Deleted "${subscription.name}"${serversInGroup > 0 ? ' and $serversInGroup server${serversInGroup > 1 ? 's' : ''}' : ''}',
                        ),
                      ),
                    ],
                  ),
                  backgroundColor: Colors.green,
                ),
              );
            },
            child: const Text(
              'Delete',
              style: TextStyle(color: Colors.red),
            ),
          ),
        ],
      ),
    );
  }

  void _confirmDeleteServers(BuildContext context, Subscription subscription) {
    final vpnProvider = Provider.of<VpnProvider>(context, listen: false);
    
    // 计算该订阅分组下的服务器数量
    final serversInGroup = vpnProvider.allServers
        .where((s) => s.group == subscription.name)
        .length;
    
    if (serversInGroup == 0) {
      ScaffoldMessenger.of(context).showSnackBar(
        const SnackBar(
          content: Row(
            children: [
              Icon(Icons.info_outline, color: Colors.white),
              SizedBox(width: 12),
              Text('No servers to delete in this group'),
            ],
          ),
          backgroundColor: Colors.blue,
        ),
      );
      return;
    }
    
    showDialog(
      context: context,
      builder: (context) => AlertDialog(
        title: Row(
          children: [
            Icon(
              Icons.delete_sweep,
              color: Colors.orange.shade700,
              size: 28,
            ),
            const SizedBox(width: 12),
            const Text('Delete All Servers?'),
          ],
        ),
        content: Column(
          mainAxisSize: MainAxisSize.min,
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Text(
              'Delete all servers in "${subscription.name}"?',
              style: const TextStyle(
                fontSize: 15,
                fontWeight: FontWeight.w500,
              ),
            ),
            const SizedBox(height: 16),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.red.shade900.withOpacity(0.2)
                    : Colors.red.shade50,
                borderRadius: BorderRadius.circular(8),
                border: Border.all(
                  color: Theme.of(context).brightness == Brightness.dark
                      ? Colors.red.shade700.withOpacity(0.5)
                      : Colors.red.shade200,
                ),
              ),
              child: Row(
                children: [
                  Icon(Icons.warning_amber_rounded, color: Colors.red.shade700, size: 20),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'This will delete $serversInGroup server${serversInGroup > 1 ? 's' : ''} from this group.',
                      style: TextStyle(
                        fontSize: 13,
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.red.shade300
                            : Colors.red.shade900,
                        fontWeight: FontWeight.w500,
                      ),
                    ),
                  ),
                ],
              ),
            ),
            const SizedBox(height: 12),
            Container(
              padding: const EdgeInsets.all(12),
              decoration: BoxDecoration(
                color: Theme.of(context).brightness == Brightness.dark
                    ? Colors.blue.shade900.withOpacity(0.2)
                    : Colors.blue.shade50,
                borderRadius: BorderRadius.circular(8),
              ),
              child: Row(
                children: [
                  Icon(
                    Icons.info_outline,
                    color: Colors.blue.shade700,
                    size: 20,
                  ),
                  const SizedBox(width: 8),
                  Expanded(
                    child: Text(
                      'The subscription will be kept. You can update it later to fetch servers again.',
                      style: TextStyle(
                        fontSize: 12,
                        color: Theme.of(context).brightness == Brightness.dark
                            ? Colors.blue.shade300
                            : Colors.black87,
                        height: 1.4,
                      ),
                    ),
                  ),
                ],
              ),
            ),
          ],
        ),
        actions: [
          TextButton(
            onPressed: () => Navigator.pop(context),
            child: const Text('Cancel'),
          ),
          ElevatedButton.icon(
            onPressed: () async {
              Navigator.pop(context);
              
              // 删除该分组下的所有服务器
              await vpnProvider.deleteServersByGroup(subscription.name);
              
              // 更新订阅的服务器数量为0
              subscription.serverCount = 0;
              final subscriptionProvider = Provider.of<SubscriptionProvider>(
                context,
                listen: false,
              );
              await subscriptionProvider.updateSubscription(subscription);
              
              if (context.mounted) {
                ScaffoldMessenger.of(context).showSnackBar(
                  SnackBar(
                    content: Row(
                      children: [
                        const Icon(Icons.check_circle, color: Colors.white),
                        const SizedBox(width: 12),
                        Expanded(
                          child: Text(
                            'Deleted $serversInGroup server${serversInGroup > 1 ? 's' : ''} from "${subscription.name}"',
                          ),
                        ),
                      ],
                    ),
                    backgroundColor: Colors.green,
                    duration: const Duration(seconds: 3),
                  ),
                );
              }
            },
            icon: const Icon(Icons.delete_sweep),
            label: const Text('Delete All Servers'),
            style: ElevatedButton.styleFrom(
              backgroundColor: Colors.red,
              foregroundColor: Colors.white,
            ),
          ),
        ],
      ),
    );
  }
}

class _SubscriptionCard extends StatelessWidget {
  final Subscription subscription;
  final VoidCallback onUpdate;
  final VoidCallback onEdit;
  final VoidCallback onDelete;
  final VoidCallback onDeleteServers;

  const _SubscriptionCard({
    required this.subscription,
    required this.onUpdate,
    required this.onEdit,
    required this.onDelete,
    required this.onDeleteServers,
  });

  @override
  Widget build(BuildContext context) {
    return Card(
      margin: const EdgeInsets.only(bottom: 16),
      child: Padding(
        padding: const EdgeInsets.all(16),
        child: Column(
          crossAxisAlignment: CrossAxisAlignment.start,
          children: [
            Row(
              children: [
                Expanded(
                  child: Text(
                    subscription.name,
                    style: const TextStyle(
                      fontSize: 18,
                      fontWeight: FontWeight.bold,
                    ),
                  ),
                ),
                IconButton(
                  icon: const Icon(Icons.refresh),
                  onPressed: onUpdate,
                  tooltip: 'Update',
                ),
                IconButton(
                  icon: const Icon(Icons.edit),
                  onPressed: onEdit,
                  tooltip: 'Edit',
                ),
                IconButton(
                  icon: const Icon(Icons.delete),
                  onPressed: onDelete,
                  tooltip: 'Delete',
                ),
              ],
            ),
            const SizedBox(height: 8),
            Row(
              children: [
                Icon(
                  Icons.dns,
                  size: 16,
                  color: Colors.grey.shade600,
                ),
                const SizedBox(width: 4),
                Text(
                  '${subscription.serverCount} server${subscription.serverCount != 1 ? 's' : ''}',
                  style: TextStyle(
                    color: Colors.grey.shade600,
                  ),
                ),
                const Spacer(),
                // 删除所有节点按钮
                if (subscription.serverCount > 0)
                  TextButton.icon(
                    onPressed: onDeleteServers,
                    icon: Icon(
                      Icons.delete_sweep,
                      size: 18,
                      color: Colors.orange.shade700,
                    ),
                    label: Text(
                      'Delete All Servers',
                      style: TextStyle(
                        fontSize: 12,
                        color: Colors.orange.shade700,
                      ),
                    ),
                    style: TextButton.styleFrom(
                      padding: const EdgeInsets.symmetric(horizontal: 8, vertical: 4),
                      minimumSize: Size.zero,
                      tapTargetSize: MaterialTapTargetSize.shrinkWrap,
                    ),
                  ),
              ],
            ),
            if (subscription.lastUpdate != null) ...[
              const SizedBox(height: 4),
              Text(
                'Last updated: ${DateFormat.yMMMd().add_jm().format(subscription.lastUpdate!)}',
                style: TextStyle(
                  fontSize: 12,
                  color: Colors.grey.shade600,
                ),
              ),
            ],
          ],
        ),
      ),
    );
  }
}
